import './App.css';
import {memo, useEffect, useState} from "react";
import {Alert, Button} from "@mui/material";
import AddIcon from '@mui/icons-material/Add';
import styled from '@emotion/styled';
import TodoListArea from "./components/TodoListArea";
import CompletedListArea from "./components/CompletedListArea";
import CreateArea from "./components/CreateArea";
import {v4 as uuidV4} from "uuid";
import TopBarArea from "./components/TopBarArea";

export type ITodoItem = {
    id: string;
    title: string;
    hasCompleted?: boolean;
};

const generateRandomString = (length = 8) => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
};

const testData = (new Array(20).fill(null)).map((_, index) => ({
    id: uuidV4(),
    title: `任务${generateRandomString()} ${index + 1}`,
}));

function App() {
    const [list, setList] = useState<ITodoItem[]>(import.meta.env.DEV ? testData : []);
    const [filteredList, setFilteredList] = useState<ITodoItem[] | null>(null);
    const [isCreatingMode, setIsCreatingMode] = useState(false);
    const [errorText, setErrorText] = useState<string | null>(null);
    const [isSearchEditing, setIsSearchEditing] = useState(false);

    useEffect(() => {
        if (!isSearchEditing) {
            setFilteredList(null);
        }
    }, [isSearchEditing]);

    const handleAddClick = () => {
        setIsCreatingMode(true);
    };

    const handleComplete = (id: string) => {
        setList(prevList =>
            prevList.map(item =>
                item.id === id ? {...item, hasCompleted: true} : item,
            ),
        );
    };

    const handleDeleteItem = (id: string) => {
        setList(prev => prev.filter(item => item.id !== id));
    };

    const handleEditItem = (id: string, title: string) => {
        // item : {
        // title: string;
        // }
        setList(prevList =>
            // const index = prevList.findIndex(i => i.id === id);
            // prevList[index].title = title;
            // return [...prevList];

            prevList.map(item =>
                ({
                    ...item,
                    title: item.id === id ? title : item.title,
                }),
            ),
        );
    };
    const handleCreateConfirm = (title: string) => {
        const newItem: ITodoItem = {
            id: uuidV4(),
            hasCompleted: false,
            title,
        };
        setList(prev => [...prev, newItem]);

        setIsCreatingMode(false);
    };

    const handleCancelEdit = () => {
        setIsCreatingMode(false);
    };

    useEffect(() => {
        if (errorText !== null) {
            const tid = setTimeout(() => setErrorText(null), 5000);
            return () => clearTimeout(tid);
        }
    }, [errorText]);

    const handleSearchTextConfirm = (text: string) => {
        setFilteredList(
            list.filter(item =>
                item.title.toLowerCase().includes(text.toLowerCase()),
            ),
        );
    };

    return (
        <MainContainer style={isSearchEditing ? {paddingTop: 160} : undefined}>
            <TodoListArea
                list={filteredList ?? list}
                onItemComplete={handleComplete}
                onEditItem={handleEditItem}
            />

            {isCreatingMode && (
                <CreateArea
                    onConfirm={handleCreateConfirm}
                    onCancel={handleCancelEdit}
                />
            )}

            {!isCreatingMode && (
                <AddButton
                    startIcon={<AddIcon/>}
                    variant="contained"
                    onClick={handleAddClick}
                >
                    添加
                </AddButton>
            )}

            {errorText && (
                <Alert style={{marginTop: 16}} severity="error">{errorText}</Alert>
            )}

            <CompletedListArea list={filteredList ?? list} onItemDelete={handleDeleteItem}/>
            <TopBarArea
                onConfirm={handleSearchTextConfirm}
                isSearchEditing={isSearchEditing}
                setIsSearchEditing={setIsSearchEditing}
            />
        </MainContainer>
    );
}

const MainContainer = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    padding: 32px 0;
`;

const AddButton = styled(Button)`
    width: 200px;
    height: 40px;
`;

export default memo(App);
